<?php

namespace JsonRpc\Services\Product;

use JsonRpc\Models\PBrand;
use JsonRpc\Services\CommonService;
use JsonRpc\Services\System\UserService;

/**
 *  用户
 * @author walkor <worker-man@qq.com>
 */
class BrandService
{
    use CommonService;

    private static function getBaseModel()
    {
        return "JsonRpc\\Models\\PBrand";
    }

    public static function ping()
    {
        return 'OK';
    }

    public static function saveData($params)
    {
        if (isset($params['id']) && $params['id']) {
            //更新
            $model = PBrand::find($params['id']);
            $model->updated_by = $params['curr_user_id'];

        } else {
            $user = UserService::getInfoById(['id' => $params['curr_user_id']]);
            //新增
            unset($params['id']);
            $model = new PBrand();
            $model->client_id = 0;
            $model->org_id = 0;
            $model->created_by = $user['id'];
            $model->updated_by = $user['id'];
            if (self::checkNameUnique(htmlspecialchars(trim($params['name'])))) {
                throw new \Exception('品牌名已存在', 400);
            }
        }
        $model->name = htmlspecialchars(trim($params['name']));
        $model->initial = htmlspecialchars(trim($params['initial']));
        if(!empty($params['pic'])) $model->pic = $params['pic']; //不为空时才保存图片
        $model->is_recommend = $params['is_recommend'];
        return $model->save();
    }

    private static function checkNameUnique($name)
    {
        return PBrand::where('name', '=',$name) ? true : false;
    }

}
